using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PHSRAG.Utility;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.InsightUtilities;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21;
using PHSRAG.Insight21.COI;
using PHSRAG.Insight21.SearchContext;

public partial class COI_DisclosureLookup : BasePage
{

    private ICachePolicy pageCachePolicy;
    private ICachePolicy cachePolicy;
    
    private DataTable dtDisclosures = null;



    private const string PageCacheKey = "pageCacheKey_D7A30B33-CA3C-443e-8020-3085A2A8CCDA";
    private const string UsersCacheKey = "usersCacheKey_40D7C440-6933-4406-805B-1BC3807C9088";
    private const string OrgsCacheKey = "orgsCacheKey_CA8CA41C-8CEF-4d73-BA22-757E88CD35B9";
    private const string DisclosureLookupPageIndexKey = "DisclosureLookupPageIndexKey_D9B2FC11-4FB4-47ad-94B2-86CD91550870";




    #region Page and Control Events

    #region OnInit
    /// <summary>
    /// Page Initialization.
    /// </summary>
    /// <param name="e">Arguments associated with the event</param>
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        cachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Session[PHSRAG.Insight21.Policy.Names.CachePolicyKey];
        pageCachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Session[PHSRAG.Insight21.Policy.Names.PageCachePolicyKey];
    }

    #endregion OnInit

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            breadCrumb.Add("Disclosure Lookup", Settings.GetKeyValue("SubNavigation.CoI.DisclosureLookupURL", string.Empty), Settings.GetKeyValue("BreadCrumb.SummaryPageLevel", 1));

            if (Page.IsPostBack)
            {
                //Setting the GridView size.
                gvDisclosures.PageSize = Settings.GetKeyValue("COIDataGrid.ItemsPerPage", 20);
            }
         }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
        finally
        {
            coiSubNavigation.AccessLevel = ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).ModuleRoleBitmask;
            coiSubNavigation.IsLoggedInUserADelegate = IsLoggedInUserADelegate;
        }
    }

    #endregion Page_Load

    #region Page_PreRender

    protected void Page_PreRender(object sender, EventArgs e)
    {
        ConsolidateListControls();
    }

    #endregion Page_PreRender

    #region COISubNavigation_OnNavigate

    protected void COISubNavigation_OnNavigate(object sender,EventArgs e)
    {
        try
        {
            PurgeCache();
            //coiSubNavigation.Reset();
            //RemovePersonIdFromIncomingCache();

        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion COISubNavigation_OnNavigate

    #region Header_BreadCrumb_OnNavigate
    
    protected void Header_BreadCrumb_OnNavigate(object sender, EventArgs e)
    {
        try
        {
            CurrentPageIndex = 0;
            //SortColumn = ColumnId;
            //SortAscending = true;
            coiSubNavigation.Reset();
            UncacheUserDetails();
        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion Header_BreadCrumb_OnNavigate

    #region ImageButton_OnCommand
    protected void ImageButton_OnCommand(object sender, CommandEventArgs e)
    {
        UserContext userContext = cachePolicy.GetCachedObject(UserContext.CacheKey) as UserContext;
        int intAdmPersonId = 0;
        intAdmPersonId = (userContext != null ? userContext.PersonId : 0);
        switch (e.CommandName)
        {
            case "FindUsers":
                lstUsersFound.DataSource = COIUserSummary.GetCOIUsersForDisclosure(intAdmPersonId, FirstName.Text, LastName.Text, UserName.Text, SupervisorFirstName.Text, SupervisorLastName.Text);
                lstUsersFound.DataValueField = "Id";
                lstUsersFound.DataTextField = "Name";
                lstUsersFound.DataBind();
                break;
            case "MoveUsersToRight":
                //Adding items to the right side.
                foreach (ListItem li in lstUsersFound.Items)
                {
                    if (li.Selected)
                    {
                        lstUsersForSearch.Items.Add(li);
                        lstUsersForSearch.SelectedIndex = -1;
                        SaveUsersToCache(li);
                    }
                }
                //Removing the items that are added
                foreach (ListItem li in lstUsersForSearch.Items)
                {
                    ListItem lstItem = lstUsersFound.Items.FindByValue(li.Value);
                    if (null != lstItem)
                        lstUsersFound.Items.Remove(lstItem);

                }
                break;
            case "MoveUsersToLeft":
                //Adding items to the right side.
                foreach (ListItem li in lstUsersForSearch.Items)
                {
                    if (li.Selected)
                    {
                        lstUsersFound.Items.Add(li);
                        RemoveUsersFromCache(li);
                    }
                }
                break;
            case "FindOrganizations":
                lstOrganizationsFound.DataSource = COIOrganizationCollection.GetOrganizations(txtOrganization.Text.Trim());
                lstOrganizationsFound.DataValueField = "Id";
                lstOrganizationsFound.DataTextField = "Name";
                lstOrganizationsFound.DataBind();
                break;
            case "MoveOrganizationsToRight":
                //Adding items to the right side.
                foreach (ListItem li in lstOrganizationsFound.Items)
                {
                    if (li.Selected)
                    {
                        lstOrganizationsForSearch.Items.Add(li);
                        lstOrganizationsForSearch.SelectedIndex = -1;
                        SaveOrgsToCache(li);
                    }
                }
                //Removing the items that are added
                foreach (ListItem li in lstOrganizationsForSearch.Items)
                {
                    ListItem lstItem = lstOrganizationsFound.Items.FindByValue(li.Value);
                    if (null != lstItem)
                        lstOrganizationsFound.Items.Remove(lstItem);

                }
                break;
            case "MoveOrganizationsToLeft":
                //Adding items to the right side.
                foreach (ListItem li in lstOrganizationsForSearch.Items)
                {
                    if (li.Selected)
                    {
                        lstOrganizationsFound.Items.Add(li);
                        RemoveOrgsFromCache(li);
                    }
                }
                break;
            case "SearchDisclosures":
                LoadDataGrid();
                break;
            case "ClearSearchCriteria":
                cachePolicy.UnCache(UsersCacheKey);
                cachePolicy.UnCache(OrgsCacheKey);
                FirstName.Text = "";
                LastName.Text = "";
                UserName.Text = "";
                SupervisorFirstName.Text = "";
                SupervisorLastName.Text = "";
                txtOrganization.Text = "";
                //Clearing the hidden controls that are used to store Users and Orgs
                hdnUsersForSearch.Value = "";
                hdnOrganizationsForSearch.Value = "";
                lstUsersForSearch.Items.Clear();
                lstOrganizationsForSearch.Items.Clear();

                lstOrganizationsFound.DataSource = null;
                lstOrganizationsFound.DataBind();
                lstOrganizationsFound.Items.Clear();
                lstUsersFound.DataSource = null;
                lstUsersFound.DataBind();
                lstUsersFound.Items.Clear();

                gridContainer.Visible = false;
                gvDisclosures.DataBind();
                break;
        }

    }

    #endregion ImageButton_OnCommand

    #endregion Page and Control Events

    #region Paging and Sorting Events


    #region Pager_OnFirstPage
    /// <summary>
    /// Occurs when the FirstPage hyperlink is clicked on the pager.
    /// The page's GridView is reloaded with the data belonging to the first page.
    /// </summary>
    /// <param name="sender">The object raising an event.</param>
    /// <param name="e">Argument associated with the event</param>
    protected void Pager_OnFirstPage(object sender, CommandEventArgs e)
    {
        try
        {
            CurrentPageIndex = 0;
            LoadDataGrid();
        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion Pager_OnFirstPage
    
    #region Pager_OnNextPage
    /// <summary>
    /// Occurs when the NextPage hyperlink is clicked on the pager.
    /// The page's GridView is reloaded with the data belonging to the next page.
    /// </summary>
    /// <param name="sender">The object raising an event.</param>
    /// <param name="e">Argument associated with the event</param>
    protected void Pager_OnNextPage(object sender, CommandEventArgs e)
    {
        try
        {
            ++CurrentPageIndex;
            LoadDataGrid();
        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion Pager_OnNextPage

    #region Pager_OnPreviousPage
    /// <summary>
    /// Occurs when the PreviousPage hyperlink is clicked on the pager.
    /// The page's DataGrid is reloaded with the data belonging to the previous page.
    /// </summary>
    /// <param name="sender">The object raising an event.</param>
    /// <param name="e">Argument associated with the event</param>
    protected void Pager_OnPreviousPage(object sender, CommandEventArgs e)
    {
        try
        {
            --CurrentPageIndex;
            LoadDataGrid();
        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion Pager_OnPreviousPage
    
    #region Pager_OnLastPage
    /// <summary>
    /// Occurs when the LastPage hyperlink is clicked on the pager.
    /// The page's GridView is reloaded with the data belonging to the last page.
    /// </summary>
    /// <param name="sender">The object raising an event.</param>
    /// <param name="e">Argument associated with the event</param>
    protected void Pager_OnLastPage(object sender, CommandEventArgs e)
    {
        try
        {
            int lastPageIndex = topPager.PageCount - 1;
            CurrentPageIndex = lastPageIndex;
            LoadDataGrid();
        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion Pager_OnLastPage
    
    #region gvDisclosures_OnSorting
    /// <summary>
    /// Sort event handler
    /// </summary>
    /// <param name="source">The object raising an event.</param>
    /// <param name="e">Argument associated with the event</param>
    protected void gvDisclosures_OnSorting(object sender, GridViewSortEventArgs e)
    {
        try
        {
            if (e.SortExpression != string.Empty)
            {
                CurrentPageIndex = 0;
               
                if (e.SortExpression == hdnSortColumn.Value)
                    hdnSortOrder.Value = (PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending == hdnSortOrder.Value) ? PHSRAG.Insight21.InsightUtilities.Constants.SortViewDescending : PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending;
                else
                    hdnSortOrder.Value = PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending;

                hdnSortColumn.Value = e.SortExpression;
                LoadDataGrid();


                

            }
        }
        catch (Exception ex)
        {
            DisplayExceptionReport(ex);
        }
    }

    #endregion gvDisclosures_OnSorting

    #region gvDisclosures_OnRowCreated

    protected void gvDisclosures_OnRowCreated(object sender,GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            Image imgSortOrder = new Image();
            foreach (TableCell tc in e.Row.Cells)
            {
                if (tc.HasControls())
                {
                    LinkButton lbLinkButton = (LinkButton)tc.Controls[0];
                    if (hdnSortColumn.Value == lbLinkButton.CommandArgument)
                    {
                        if (hdnSortOrder.Value == PHSRAG.Insight21.InsightUtilities.Constants.SortViewAscending)
                            imgSortOrder.ImageUrl = "../Images/arrowUp.gif";
                        else
                            imgSortOrder.ImageUrl = "../Images/arrowDown.gif";
                        tc.VerticalAlign = VerticalAlign.Bottom;
                        tc.Controls.Add(imgSortOrder);
                    }
                }
            }
        }
    }

    #endregion gvDisclosures_OnRowCreated

    #endregion Paging and Sorting Events


    #region Properties

    
    private int MaxCOIUsersForSearch
    {
        get
        {   int intMaxCOIUsersForSearch;
            intMaxCOIUsersForSearch = Settings.GetKeyValue("COIDisclosure.MaxCOIUsersForSearch", 20);
            return intMaxCOIUsersForSearch;
        }
    }

    private int MaxCOIOrgsForSearch
    {
        get
        {
            int intMaxCOIOrgsForSearch;
            intMaxCOIOrgsForSearch = Settings.GetKeyValue("COIDisclosure.MaxCOIOrgsForSearch", 20);
            return intMaxCOIOrgsForSearch;
        }
    }

    #region SelectedCOIUsers
    private string strSelectedCOIUsers = null;
    private string SelectedCOIUsers
    {
        get 
        { 
            strSelectedCOIUsers = GetString(GetUsersFromCache(), ",",true);
            return strSelectedCOIUsers; 
        }
    }

    #endregion SelectedCOIUsers

    #region SelectedCOIOrgs
    private string strSelectedCOIOrgs = null;
    private string SelectedCOIOrgs
    {
        get
        {
            strSelectedCOIOrgs = GetString(GetOrgsFromCache(), ",",false);
            return strSelectedCOIOrgs;
        }
    }
    #endregion SelectedCOIOrgs

    #region CurrentPageIndex
    /// <summary>
    /// Get/Set the current page within the datagrid for display. This information persists across page loads.
    /// </summary>
    private int CurrentPageIndex
    {
        get
        {
            Hashtable h = pageCachePolicy.GetCachedObject(Keys.DisclosureLookupPageKey) as Hashtable;
            return (h == null || h[DisclosureLookupPageIndexKey] == null) ? 0 : (int)h[DisclosureLookupPageIndexKey];
        }
        set
        {
            Hashtable h = pageCachePolicy.GetCachedObject(Keys.DisclosureLookupPageKey) as Hashtable ?? new Hashtable();

            h[DisclosureLookupPageIndexKey] = value;
            gvDisclosures.PageIndex = value;
            pageCachePolicy.Cache(Keys.DisclosureLookupPageKey, h);
        }
    }

    #endregion CurrentPageIndex

    #region IsLoggedInUserADelegate

    /// <summary>
    /// Get delegate status of the loggedIn user.
    /// </summary>
    /// 
    private bool IsLoggedInUserADelegate
    {
        get
        {
            int loggedInUserId = ((UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey)).PersonId;
            return COIUserSummary.IsLoggedInUserADelegate(loggedInUserId, DataAccess.GetConnectionString());
        }
    }

    #endregion IsLoggedInUserADelegate

    #endregion Properties
    
    #region Private methods

    #region ConsolidateListControls

    private void ConsolidateListControls()
    {
       
        //For COI Users
        Hashtable htUsers = GetUsersFromCache();
        lstUsersForSearch.Items.Clear();
        foreach (DictionaryEntry de in htUsers)
        {
            lstUsersForSearch.Items.Add(new ListItem(de.Value.ToString(),de.Key.ToString()));
            ListItem objListItem = lstUsersFound.Items.FindByValue(de.Key.ToString());
            if (null != objListItem)
                lstUsersFound.Items.Remove(objListItem);
        }

        //For COI Organizations
        Hashtable htOrgs = GetOrgsFromCache();
        lstOrganizationsForSearch.Items.Clear();
        foreach (DictionaryEntry de in htOrgs)
        {
            lstOrganizationsForSearch.Items.Add(new ListItem(de.Value.ToString(), de.Key.ToString()));
            ListItem objListItem = lstOrganizationsFound.Items.FindByValue(de.Key.ToString());
            if (null != objListItem)
                lstOrganizationsFound.Items.Remove(objListItem);
        }

    }

    

    #endregion ConsolidateListControls

    #region DisplayExceptionReport
    /// <summary>
    /// Displays an error message on the screen to the user with the exception, and all
    /// inner exception messages.
    /// </summary>
    /// <param name="ex">The exception to report on</param>
    private void DisplayExceptionReport(Exception ex)
    {
        annunciator.Title = PHSRAG.Insight21.InsightUtilities.Constants.Annunciator.Title;
        annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
    }

    #endregion DisplayExceptionReport

    #region UncacheUserDetails
    /// <summary>
    /// Remove the admpersonid and the username, if exists, from the cache
    /// Remove the pagecache
    /// </summary>
    private void UncacheUserDetails()
    {
        Hashtable incomingData = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;
        if (incomingData != null)
        {
            if (incomingData.ContainsKey(Keys.FullNameKey))
            {
                incomingData.Remove(Keys.FullNameKey);
            }
            if (incomingData.ContainsKey(Keys.AdmPersonIdKey))
            {
                incomingData.Remove(Keys.AdmPersonIdKey);
            }
        }
        pageCachePolicy.UnCache(PageCacheKey);
    }

    #endregion UncacheUserDetails

    #region LoadDataGrid
    /// <summary>	
    /// Loads the COIUser Summary details only for those to displayed on the page.
    /// </summary>
    private void LoadDataGrid()
    {
        //SetPersonIdToImpersonate();
        int intStartPageIndex = CurrentPageIndex;
        int intEndingPageIndex = CurrentPageIndex + 1;
        int intPageSize = gvDisclosures.PageSize;
        string strOrderBy = hdnSortColumn.Value + " " + hdnSortOrder.Value;
        dtDisclosures = COIUserSummary.GetDisclosuresForCOIUsers(SelectedCOIUsers,SelectedCOIOrgs, strOrderBy, intPageSize, intStartPageIndex, intEndingPageIndex);

        if (null != dtDisclosures)
        {

            bottomPager.RecordCount = topPager.RecordCount = (dtDisclosures.Rows.Count > 0 ? Convert.ToInt32(dtDisclosures.Rows[0]["RecordCount"].ToString()) : 0);
            int currentPageIndex = CurrentPageIndex;
            int pageCount = (topPager.RecordCount / gvDisclosures.PageSize) +
                (((topPager.RecordCount % gvDisclosures.PageSize) == 0) ? 0 : 1);
            bottomPager.PageCount = topPager.PageCount = pageCount;
            bottomPager.CurrentPage = topPager.CurrentPage = currentPageIndex + 1;

            gvDisclosures.DataSource = dtDisclosures;
            gvDisclosures.DataBind();

            if (dtDisclosures.Rows.Count == 0)
            {
                gridContainer.Visible = false;
                annunciator.Message = "The search criteria yielded no results.";
            }
            else
            {
                gridContainer.Visible = true;
                annunciator.Message = string.Empty;
                recordCount.Text = topPager.RecordCount.ToString();
                ManagePagination();
                ManageNavigationLinks();
            }
        }
        else
        {
            gridContainer.Visible = false;
            annunciator.Message = string.Empty;
        }
    }

    #endregion LoadDataGrid

    #region ManageNavigationLinks
    /// <summary>
    /// Enables or Disables links to other pages within the grid
    /// </summary>
    private void ManageNavigationLinks()
    {
        bottomPager.EnableFirstPage = topPager.EnableFirstPage =
            bottomPager.EnablePreviousPage = topPager.EnablePreviousPage =
                (gvDisclosures.PageIndex != 0);

        bottomPager.EnableLastPage = topPager.EnableLastPage =
            bottomPager.EnableNextPage = topPager.EnableNextPage =
                (gvDisclosures.PageIndex != (topPager.PageCount - 1));
    }

    #endregion ManageNavigationLinks

    #region ManagePagination
    /// <summary>
    /// Pagination management
    /// </summary>
    private void ManagePagination()
    {
        int currentPageIndex = CurrentPageIndex;
        gvDisclosures.PageIndex = currentPageIndex;

        int startIndex = currentPageIndex * gvDisclosures.PageSize;
        bottomPager.FirstRecord = topPager.FirstRecord = startIndex + 1;

        int lastRecord = topPager.RecordCount = bottomPager.RecordCount;
        bottomPager.LastRecord = topPager.LastRecord =
            Math.Min(startIndex + gvDisclosures.PageSize, lastRecord);
    }

    #endregion ManagePagination


    #region PurgeCache

    private void PurgeCache()
    {
        cachePolicy.UnCache(UsersCacheKey);
        cachePolicy.UnCache(OrgsCacheKey);
    }

    #endregion PurgeCache

    #region GetString
    private string GetString(Hashtable ht, string strSeperator,bool blnUseKey) 
    {
        StringBuilder sb = new StringBuilder();
        foreach (DictionaryEntry de in ht)
        {   if(blnUseKey)
                sb.Append(de.Key.ToString() + strSeperator);
            else
                sb.Append("'" + de.Value.ToString().Replace("'","''") + "'"+ strSeperator);
        }
        if (sb.Length > 0)
            return sb.ToString().Substring(0, sb.Length - 1);
        else
            return "";
    }
    #endregion GetString

    #region GetUsersFromCache

    private Hashtable GetUsersFromCache()
    {
        Hashtable usersDictionary = (Hashtable)cachePolicy.GetCachedObject(UsersCacheKey) as Hashtable;
        if (usersDictionary == null)
        {
            usersDictionary = new Hashtable();
        }
        return usersDictionary;
    }

    #endregion GetUsersFromCache

    #region GetOrgsFromCache
    private Hashtable GetOrgsFromCache()
    {
        Hashtable orgsDictionary = (Hashtable)cachePolicy.GetCachedObject(OrgsCacheKey) as Hashtable;
        if (orgsDictionary == null)
        {
            orgsDictionary = new Hashtable();
        }
        return orgsDictionary;
    }

    #endregion GetOrgsFromCache

   

    #region SaveUsersToCache
    private void SaveUsersToCache(ListItem li)
    {
        Hashtable usersDictionary = GetUsersFromCache();
        if (!usersDictionary.Contains(li.Value) && usersDictionary.Count < MaxCOIUsersForSearch)
            usersDictionary.Add(li.Value, li.Text);
        cachePolicy.Cache(UsersCacheKey, usersDictionary);
    }
    #endregion SaveUsersToCache

    #region RemoveUsersFromCache
    private void RemoveUsersFromCache(ListItem li)
    {
        Hashtable usersDictionary = GetUsersFromCache();
        if (usersDictionary.Contains(li.Value))
            usersDictionary.Remove(li.Value);
        cachePolicy.Cache(UsersCacheKey, usersDictionary);

    }

    #endregion RemoveUsersFromCache

    #region SaveOrgsToCache

    private void SaveOrgsToCache(ListItem li)
    {
        Hashtable orgsDictionary = GetOrgsFromCache();

        if (!orgsDictionary.Contains(li.Value) && orgsDictionary.Count < MaxCOIOrgsForSearch)
            orgsDictionary.Add(li.Value, li.Text);
        cachePolicy.Cache(OrgsCacheKey, orgsDictionary);
    }

    #endregion SaveOrgsToCache
    #region RemoveOrgsFromCache
    private void RemoveOrgsFromCache(ListItem li)
    {
        Hashtable orgsDictionary = GetOrgsFromCache();
        if (orgsDictionary.Contains(li.Value))
            orgsDictionary.Remove(li.Value);
        cachePolicy.Cache(OrgsCacheKey, orgsDictionary);

    }

    #endregion RemoveOrgsFromCache

   

    #endregion Private Methods

    #region MimicSearch

   

    private void SetSearchCriteria()
    {
        cachePolicy = (PHSRAG.Insight21.Policy.ICachePolicy)Page.Session[PHSRAG.Insight21.Policy.Names.CachePolicyKey];
        COISearchContext searchContext = cachePolicy.GetCachedObject(COISearchContext.CacheKey) as COISearchContext;
        if (searchContext == null)
        {
            searchContext = new COISearchContext(cachePolicy);
            searchContext.Load(DataAccess.ConnectionString);
            searchContext.Cache();
        }
        //EnsureChildControls();
        //base.OnInit(e);
        searchContext.GetSearchCriteria(Page.Request.Url.ToString(), GetControlCollection());
    }

   
    private ControlCollection GetControlCollection()
    {
        PHSRAG.Insight21.InsightWebControls.COISearch coiSearch = new PHSRAG.Insight21.InsightWebControls.COISearch();
        ControlCollection controlCollection = new ControlCollection(coiSearch);
        controlCollection.Add(LastName);
        controlCollection.Add(FirstName);
        controlCollection.Add(UserName);
        controlCollection.Add(SupervisorLastName);
        controlCollection.Add(SupervisorFirstName);
        return controlCollection;
    }



    private const int defaultSelectedIndex = -1;
    private void SetControlState(SearchCriteria searchCriteria)
    {
        if (searchCriteria != null)
        {
            foreach (string key in searchCriteria.Keys)
            {
                Control c = FindControl(key);
                if (c != null)
                {
                    DropDownList ddl = c as DropDownList;
                    if (ddl != null)
                    {
                        ListItem item = ddl.Items.FindByValue(searchCriteria[key]);
                        if (item != null)
                            ddl.SelectedIndex = ddl.Items.IndexOf(item);
                        continue;
                    }

                    TextBox txt = c as TextBox;
                    if (txt != null)
                    {
                        txt.Text = searchCriteria[key].ToString();
                        continue;
                    }

                    //Calendar cal = c as Calendar;
                    //if (cal != null)
                    //{
                    //    cal.Prompt = searchCriteria[key].ToString();
                    //    continue;
                    //}

                    CheckBox cb = c as CheckBox;
                    if (cb != null)
                    {
                        cb.Checked = Convert.ToBoolean(searchCriteria[key]);
                        continue;
                    }

                    ListBox lb = c as ListBox;
                    if (lb != null)
                    {
                        string[] selectedValueList = searchCriteria[key].Split(',');
                        lb.SelectedIndex = defaultSelectedIndex;
                        if (selectedValueList != null)
                        {
                            foreach (string selectedValue in selectedValueList)
                            {
                                lb.Items.FindByValue(selectedValue.Substring(1, selectedValue.Length - 2)).Selected = true;
                            }
                        }
                        continue;
                    }

                    /// Controls which are Label are subject to having their state set. However, not all labels are
                    /// deemed to contribute to the search criteria (for example, the labels which display selections made in one
                    /// or more of the pickers). Such lables are ignored (see comments in CommonSearch.CreateControls()).
                    Label lbl = c as Label;
                    if (lbl != null && lbl.Attributes["PickerSelection"] != null)
                    {
                        lbl.Visible = true;
                        continue;
                    }
                }
            }
        }
    }



    #endregion MimicSearch


    #region Deprecated Code
    private void ConsolidateListControls_old()//HiddenField hdnHiddenField, ListControl lstListControl)
    {
        string strAdmPersonIds = "";
        string strCOIOrgIds = "";

        strAdmPersonIds = hdnUsersForSearch.Value;
        strCOIOrgIds = hdnOrganizationsForSearch.Value;
        //For COI Users
        lstUsersForSearch.Items.Clear();
        if (string.Empty != strAdmPersonIds)
        {
            string[] arrAdmPersonIds = strAdmPersonIds.Split(new char[] { ',' });
            for (int intCounter = 0; intCounter < arrAdmPersonIds.Length; intCounter++)
            {
                ListItem objListItem = lstUsersFound.Items.FindByValue(arrAdmPersonIds[intCounter].ToString());
                if (null != objListItem)
                {
                    lstUsersForSearch.Items.Add(objListItem);
                    lstUsersFound.Items.Remove(objListItem);
                }
            }
        }
        //For COI Organizations
        lstOrganizationsForSearch.Items.Clear();
        if (string.Empty != strCOIOrgIds)
        {
            string[] arrCOIOrgs = strCOIOrgIds.Split(new char[] { ',' });
            for (int intCounter = 0; intCounter < arrCOIOrgs.Length; intCounter++)
            {
                ListItem objListItem = lstOrganizationsFound.Items.FindByValue(arrCOIOrgs[intCounter].ToString());
                if (null != objListItem)
                {
                    lstOrganizationsForSearch.Items.Add(objListItem);
                    lstOrganizationsFound.Items.Remove(objListItem);
                }
            }
        }

    }

    #endregion Deprecated Code
}
